package com.siruier.boss.ui.activity.user

import android.content.Intent
import android.net.Uri
import android.view.View
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.forEach
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import com.kingja.loadsir.core.LoadService
import com.siruier.boss.R
import com.siruier.boss.api.CustomerRecord
import com.siruier.boss.api.CustomerTotal
import com.siruier.boss.api.LOGIN_API_SERVICE
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.loginApi
import com.siruier.boss.bean.CmTypeBean
import com.siruier.boss.bean.CmUserAddBean
import com.siruier.boss.bean.UserLevelEnum
import com.siruier.boss.common.handleLoginName
import com.siruier.boss.databinding.ActivityCustomerManageBinding
import com.siruier.boss.databinding.ItemCmTypeBinding
import com.siruier.boss.databinding.ItemCmUserAddBinding
import com.siruier.boss.databinding.ItemCmUserBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.base.BaseSignCheckAdapter
import com.siruier.boss.ui.dialog.InputDialog
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.ext.*
import com.siruier.boss.ui.helper.RefreshHelper
import com.siruier.boss.ui.helper.loadsir.LoadSirHelper
import com.siruier.boss.ui.utils.FullyGridLayoutManager
import com.siruier.boss.ui.utils.Utils


class CustomerManageActivity : BaseActivity<ActivityCustomerManageBinding>() {
    private lateinit var totalRootLoadService: LoadService<*>
    private val mCmTypeAdapter = CmTypeAdapter()
    private val mCmUserAddAdapter = CmUserAddAdapter()
    private val mCmUserAdapter = CmUserAdapter()
    private lateinit var mRefreshHelper: RefreshHelper<CustomerRecord>

    override fun initView() {
        Utils.invasionStatusBar(this)
        Utils.setDefaultStatusBarFont(this, false)
        bindViewClick(vb.buttonSearch)

        totalRootLoadService = LoadSirHelper.register(vb.llTotalRoot, listener = ::loadTotalData)
        totalRootLoadService.showLoadingCallback()

        mCmTypeAdapter.setOnClickAdapterListenter(::onClick)

        mRefreshHelper = RefreshHelper(vb.refreshLayout, vb.rvUser, mCmUserAdapter, listener = ::loadUser)
        mCmUserAdapter.setOnClickAdapterListenter(::onClickUser)
        loadTotalData()
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.buttonSearch -> {
                Utils.hideSoftInput(this)
                loadUser()
            }
        }
    }

    private fun onClick(v: View?, position: Int) {
        loadUser()
    }

    private fun onClickUser(v: View?, position: Int) {
        val mCustomerRecord = mCmUserAdapter.getItem(position)
        when (v?.id) {
            R.id.tv_name -> {
                InputDialog(mThis, "备注", "请输入备注") {
                    if (it.isNotBlank()) {
                        launchUI({
                            loginApi.setRemark(it, mCustomerRecord.userId).toData()
                            mCustomerRecord.nickName = it
                            mCmUserAdapter.notifyItemChanged(position)
                        }, ApiObserver(mThis))
                    }
                }.show()
            }
            else -> {
                if ("1" == mCmUserAdapter.getItem(position).type) {
                    showAlertDialog {
                        title(title = "完整手机号")
                        message(message = mCustomerRecord.phone)
                        negativeButton(name = "复制") {
                            mCustomerRecord.phone.clipboard()
                        }
                        positiveButton(name = "拨打") {
                            val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mCustomerRecord.phone))
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                            startActivity(intent)
                        }
                    }
                }
            }
        }
    }

    private fun loadTotalData() {
        launchUI({
            val mCustomerTotal = loginApi.customerTotal().toData() ?: CustomerTotal()
            mCmTypeAdapter.datas = mutableListOf(
                CmTypeBean("全部用户", null, mCustomerTotal.userTotal, true),
                CmTypeBean(UserLevelEnum.BOSS.levelName, 3, mCustomerTotal.bossTotal),
                CmTypeBean(UserLevelEnum.AGENT.levelName, 2, mCustomerTotal.agentTotal),
                CmTypeBean(UserLevelEnum.MEMBER.levelName, 1, mCustomerTotal.memberTotal),
            )
            vb.rvCmType.layoutManager = FullyGridLayoutManager(mThis, 4)
            vb.rvCmType.adapter = mCmTypeAdapter
            (vb.rvCmType.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false

            mCmUserAddAdapter.datas = mutableListOf(
                CmUserAddBean("今日新增", mCustomerTotal.todayTotal),
                CmUserAddBean("今日${UserLevelEnum.BOSS.levelName}新增", mCustomerTotal.todayBoss),
                CmUserAddBean("今日${UserLevelEnum.AGENT.levelName}新增", mCustomerTotal.todayAgent),
                CmUserAddBean("今日${UserLevelEnum.MEMBER.levelName}新增", mCustomerTotal.todayUser),
            )
            vb.rvCmAdd.layoutManager = FullyGridLayoutManager(mThis, 4)
            vb.rvCmAdd.adapter = mCmUserAddAdapter
            (vb.rvCmAdd.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false

            customerRecord()
        }, ApiObserver(loadService = totalRootLoadService, apiObserver = mRefreshHelper.handApiObserver()))
    }

    private fun loadUser() {
        launchUI({ customerRecord() }, mRefreshHelper.handApiObserver())
    }

    private suspend fun customerRecord(): MutableList<CustomerRecord>? {
        return LOGIN_API_SERVICE.customerRecord(mRefreshHelper.page, mCmTypeAdapter.getCheck().type, vb.etPhone.value)
            .toData()?.records
    }

    class CmTypeAdapter : BaseSignCheckAdapter<ItemCmTypeBinding, CmTypeBean>() {

        override fun onBindViewHolder(vb: ItemCmTypeBinding, bean: CmTypeBean, position: Int) {
            vb.tvNum.text = "${bean.typeNum}"
            if (bean.check) {
                ViewCompat.setBackground(vb.tvNum, R.drawable.bg_cm_type_check.drawable)
                vb.tvNum.setTextColor(R.color.stock_cm_type.toColor())
                vb.ivCmCheck.isVisible = true
            } else {
                ViewCompat.setBackground(vb.tvNum, R.drawable.bg_cm_type_un_check.drawable)
                vb.tvNum.setTextColor(R.color.text_color.toColor())
                vb.ivCmCheck.isVisible = false
            }
            vb.tvCmTypeName.text = bean.typeName
            setViewClick(position, vb.root)
        }
    }

    class CmUserAddAdapter : BaseRecyclerAdapter<ItemCmUserAddBinding, CmUserAddBean>() {

        override fun onBindViewHolder(vb: ItemCmUserAddBinding, bean: CmUserAddBean, position: Int) {
            vb.tvNum.text = "+${bean.typeNum}"
            if (bean.typeNum > 0) {
                ViewCompat.setBackground(vb.tvNum, R.drawable.bg_cm_user_add.drawable)
                vb.tvNum.setTextColor(R.color.white.toColor())
            } else {
                ViewCompat.setBackground(vb.tvNum, R.drawable.bg_cm_user_no_add.drawable)
                vb.tvNum.setTextColor(R.color.text_hint_color_2.toColor())
            }
            vb.tvCmTypeName.text = bean.typeName
            setViewClick(position, vb.root)
        }
    }

    class CmUserAdapter : BaseRecyclerAdapter<ItemCmUserBinding, CustomerRecord>() {

        override fun onBindViewHolder(vb: ItemCmUserBinding, bean: CustomerRecord, position: Int) {
            vb.tvPhone.text = handleLoginName(bean.phone)
            vb.tvName.text = bean.nickName.ifBlank { "暂无" }
            vb.tvLevel.text = bean.userLevelDesc
            vb.tvType.text = if ("1" == bean.type) "直推" else "团队"
            vb.tvAddTime.text = bean.addDate.ifBlank {
                if (bean.addTime.isNotEmpty()) {
                    bean.addTime.split("T")[0]
                } else {
                    ""
                }
            }
            vb.root.forEach {
                if (it is TextView) {
                    it.setTextColor(
                        if (bean.direct == 1) {
                            R.color.main_color.toColor()
                        } else {
                            R.color.text_color.toColor()
                        }
                    )
                }
            }
            setViewClick(position, vb.root, vb.tvName)
        }
    }
}